
package com.example.client;

import com.alibaba.fastjson.JSON;
import com.example.client.entity.UserAuthorityDTO;
import com.example.client.entity.UserDetail;
import com.yjb.common.base.constant.AuthConstant;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//网关传入的用户权限信息添加到安全上下文
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String json = httpServletRequest.getHeader(AuthConstant.AUTHENTICATION);
        if (json != null) {
            //1.解析token
            UserAuthorityDTO userAuthorityDTO = JSON.parseObject(json, UserAuthorityDTO.class);
            System.out.println(userAuthorityDTO);
            String[] authorities = userAuthorityDTO.getAuthorities();
            UserDetail userDetail = new UserDetail(userAuthorityDTO.getUserName(), "", AuthorityUtils.createAuthorityList(authorities));
            //2.新建并填充authentication
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetail, null, AuthorityUtils.createAuthorityList(authorities));
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                    httpServletRequest));
            //3.将authentication保存进安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
